class Dep {
  constructor() {
    this.subscribers = new Set()
  }

  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect)
    }
  }

  notify() {
    this.subscribers.forEach(effect => {
      effect()
    })
  }
}

let activeEffect = null

function watchEffect(effect) {
  activeEffect = effect
  effect()
  // dep.depend()
  activeEffect = null
}


const targetMap = new WeakMap()
function getDep(target, key) {
  // 1.根据target对象取出对应的Map对象
  let depsMap = targetMap.get(target)
  if (!depsMap) {
    depsMap = new Map()
    targetMap.set(target, depsMap)
  }

  // 取出具体的dep对象
  let dep = depsMap.get(key)
  if (!dep) {
    dep = new Dep()
    depsMap.set(key, dep)
  }
  return dep
}

function reactive(raw) {
  Object.keys(raw).forEach(key => {
    const dep = getDep(raw, key)
    let value = raw[key]
    Object.defineProperty(raw, key, {
      get() {
        dep.depend()
        return value
      },
      set(newValue) {
        if (newValue !== value) {
          value = newValue
          dep.notify()
        }
      }
    })
  })
  console.log(raw);
  return raw
}

const dep = new Dep()



const info = reactive({
  name: 'lhh'
})

const user = reactive({
  old: 18
})

watchEffect(function logName() {
  console.log(info.name);
})

watchEffect(function logUser() {
  // console.log(user.old);
})

info.name = 'why'
dep.notify()
